-- UISphinx
-- Created by zouyb Sep/25/2015
-- 狮身人面像

UISphinx = class("UISphinx", function()
    return cc.Layer:create();
end);

function UISphinx.create(gridData)
    return UISphinx.new(gridData);
end

-- 按钮数量
local BTN_COUNT = 4;

-- 构造函数
function UISphinx:ctor(gridData)
    self:setName("UISphinx");

    local node = cc.CSLoader:createNode("layout/dungeon/BuildingView4.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.gridData  = gridData;

	-- 当前的谜语
	self.riddleConfig = RiddleM.query(self.gridData.riddle_class, self.gridData.riddle_id);
    assert(self.riddleConfig ~= nil, "找不到Riddle配置 riddle_class: " .. self.gridData.riddle_class .. ", riddle_id:" .. self.gridData.riddle_id);

    -- 洗牌（随机打乱顺序）
    if not gridData.randomOptions then
        local options = {};
        local num = #self.riddleConfig.option;
        for index = 1, num do
            options[index] = index;
        end
        for index = num, 1, -1 do
            local rand = math.random(index);
            local oldOption = options[index];

            options[index] = options[rand];
            options[rand]  = oldOption;
        end
        gridData.randomOptions = options;
    end

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISphinx:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 答错惩罚效果
function UISphinx:playSphinxPunishEffect(pos, damage)
    local uiDungeon = UIDungeonMgr.getCurLevel();
    local uiGrid = uiDungeon:getAllGrids()[pos];
    local effectParent = UIDungeonMgr:getCurLevel():getEffectParent();

    local worldPos = uiGrid:convertToWorldSpace(cc.p(0, 0));
    local gridPos = effectParent:convertToNodeSpace(worldPos);

    -- 狮身人面像发怒
    playEffect(effectParent, 1258, gridPos.x, gridPos.y - 23);
    AudioM.playFx("bloody_trap");
    local function delay()
        local heroPos = UIDungeonMgr.getCurLevel():getHeroPos();

        -- 闪电特效
        playEffect(effectParent, 1259, heroPos.x + 10, heroPos.y - 75);

        local function showDamage()
            -- 屏幕震动
            playShakeEffect(UIDungeonMgr.getCurLevel(), 0.03, 4, 4);
            AudioM.playFx("skill_shandian");
            -- 播放伤害效果
            EventMgr.fire(event.HERO_DAMAGED, { ["damage"] = damage, });

            -- 播放玩家受创动作
            UIDungeonMgr:getCurLevel():switchHeroAction(HERO_ACTION_DAMAGED);


            if  ME.user:die() then
                -- 先初始化动作序列
                SkillM.initSequence(ME.user, ME.user, PHYSIC_ATTACK);
                -- 增加死亡动作
                SkillM.getSequence(ME.user):die(ME.user, ME.user, damage, PHYSIC_ATTACK);
            end

        end
        performWithDelay(uiGrid, showDamage, 0.7);

        UIMgr.getCurrentScene():removeFormByName("UISphinx");
    end
    performWithDelay(uiGrid, delay, 0.6);
end

-- 注册事件处理回调函数
function UISphinx:registerEventCallback()

    -- 答题错误的回调处理
    EventMgr.register("UISphinx", event.RIDDLE_PUNISH_DAMAGE, function(para)
        -- 播放答错效果
        local pos = para["pos"];
        local damage = para["damage"];

        local function delay()
            self:playSphinxPunishEffect(pos, damage);
        end
        performWithDelay(self, delay, 0.2);
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UISphinx 界面析构清理");
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

            -- 移除所有事件回调
            EventMgr.removeAll("UISphinx");

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UISphinx:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UISphinx");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

	-- 按钮标题
	local buttonTitles = self.riddleConfig.option;

    -- 注册按钮点击事件
    self.buttons = {};
    for i = 1, BTN_COUNT do
        local btn = findChildByName(node, "CT/btn"..i);
        table.insert(self.buttons, btn);
        local function onOkClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_select");

				if RiddleM.isGuessRight(self.gridData.riddle_class, self.gridData.riddle_id, self.gridData.randomOptions[i]) then
					alert(getLocStr("sphinx_guess_right"));
				else
					alert(getLocStr("sphinx_guess_wrong"));
				end

				if 1 == DungeonActionM.go("guess_sphinx", self.gridData:getPos(), self.gridData.randomOptions[i]) then
				    -- 回答正确，界面直接关闭
				    UIMgr.getCurrentScene():removeFormByName("UISphinx");
				else
				    -- 回答错误，界面先隐藏，播放闪电效果后再隐藏
				    self:setVisible(false);
                    if UIDungeonMgr:getCurLevel() then
                        UIDungeonMgr:getCurLevel():showMenu();
                    end
				end
            end
        end
        AddTouchEventListener(btn, onOkClick);
        TextStyleM.setTextStyle(btn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btn:setTitleText(buttonTitles[self.gridData.randomOptions[i]]);
    end
end

-- 重绘
function UISphinx:redraw()
    -- 查询建筑配置
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    local descLabel  = findChildByName(self.node, "CT/desc");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local kerning, kerning2 = 0, 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning, kerning2 = -3, -1;
    end

    titleLabel:setString(buildingInfo["title"]);
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);
    iconImg:loadTexture(iconPath);
    local iconSize = iconImg:getContentSize();

    iconImg:setScale(1.3);
    TextStyleM.setArtWordTitleStyle(titleLabel);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning2);

	local desc = self.riddleConfig.riddle;
    applyString(descLabel, desc);
end






